package com.not_found404.bilibilimerge;

import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        showAlertDialog();
        initView();
    }

    private RecyclerView mRecyclerView;
    private Context c;
    private Tools tool;
    private CheckBox cb_all_check;

    private File out;

    private LinearLayout layout_linear;
    private void initView() {
        cb_all_check = (CheckBox)findViewById(R.id.cb_all_check);
        cb_all_check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog("确定合并所有视频吗？",0);
            }
        });
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(this));

        out = new File(Environment.getExternalStorageDirectory() + "/merge");

        layout_linear = (LinearLayout) findViewById(R.id.layout_linear);
        if (!FileUtils.isPkgInstalled(this,"tv.danmaku.bili")){
            Toast.makeText(this,"您手机上未安装哔哩哔哩客户端",Toast.LENGTH_SHORT).show();
        }else {
            try {
                c = createPackageContext("tv.danmaku.bili",
                        Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            tool = new Tools();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    scanFiles();
                    handler.obtainMessage(TYPE_COMPLETE).sendToTarget();
                }
            }).start();
        }

    }

    public static final int TYPE_CONTINUE = 0;
    public static final int TYPE_COMPLETE = 1;
    public static final int TYPE_ERROR = 2;

    private SimpleAdapter adapter;
    private Handler dialogHandler;

    public Handler getHandler() {
        return handler;
    }

    public static final int MERGE_COMPLETE = 1001;
    public static final int MERGE_ERRER = 1002;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case TYPE_COMPLETE:
                    fragment.dismiss();
                    if (adapter == null) {
                        adapter = new SimpleAdapter(bean_list);
                        adapter.bindToRecyclerView(mRecyclerView);
                        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(BaseQuickAdapter adapter, View view, final int position) {
                                showDialog("确定合并该视频吗？",position);
                            }
                        });
                    } else {
                        adapter.setNewData(bean_list);
                    }
                    break;
                case MERGE_COMPLETE:
                    Snackbar snackbar= SnackbarUtil.ShortSnackbar(layout_linear,"视频合并完成,保存在/sdcard/merge"
                            ,Color.parseColor("#A9B9CB"),Color.WHITE);
                    SnackbarUtil.SnackbarAddView(snackbar,R.layout.item_snakebar,0);
                    snackbar.show();
                    break;
            }
        }
    };

    private void merge_one(final int position) {
        showAlertDialog();
        new Thread(new Runnable() {
            @Override
            public void run() {
                String path = c.getExternalCacheDir().getParentFile().getAbsolutePath()
                        + "/download";
                String newPath = out.getAbsolutePath() + "/copy";
                dialogHandler.obtainMessage(CustomDialogFragment.CONTINUE,
                        "开始复制原文件...").sendToTarget();

                dialogHandler.obtainMessage(CustomDialogFragment.CONTINUE,
                        "开始合并...").sendToTarget();
                File file = new File(path);
                File[] files = file.listFiles();
                for (File f: files){
                    if (f.getName().equals(
                            String.valueOf(bean_list.get(position).getAvid()))){
                        try {
                            FileUtils.copy(f.getAbsolutePath(),newPath);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        File file1 = new File(newPath);
                        tool.doMerge(file1,out,dialogHandler);
                        FileUtils.deleteFolder(file1);
                    }
                }
            }
        }).start();
    }

    List<ListBean.Bean> bean_list = new ArrayList<>();

    private CustomDialogFragment fragment;

    public void showAlertDialog() {

        if (fragment == null){
            fragment = new CustomDialogFragment();
            dialogHandler = fragment.getHandler();
            fragment.show(getSupportFragmentManager(), "dialog");
        }else {
            fragment.show(getSupportFragmentManager(), "dialog");
        }


    }

    long file_size = 0;
    int count = 0;

    private void scanFiles() {
//        File file = new File(Environment.getExternalStorageDirectory()
//                + "/Android/data/tv.danmaku.bili/download");
        File file = new File(c.getExternalCacheDir().getParentFile().getAbsolutePath()
                + "/download");
        File[] files = file.listFiles();
        if (files != null || files.length > 0) {
            for (File f : files) {
                //1、2、3、4...分p
                File[] files_p = null;
                if (f.isDirectory()) {
                    files_p = f.listFiles();
                }
                //添加的bean
                ListBean.Bean bean_add = null;

                if (files_p != null) {
                    //每一p
                    for (final File ff : files_p) {



                        File[] ffs = ff.listFiles();
                        for (int i = 0; i < ffs.length; i++) {
                            File entry_file = ffs[i];
                            if (entry_file.getName().equals("entry.json")) {
                                String json_name = null;
                                try {
                                    BufferedReader reader =
                                            new BufferedReader(new InputStreamReader(
                                                    new FileInputStream(entry_file)));
                                    json_name = reader.readLine();
                                    reader.close();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                Gson gson = new Gson();
                                if (i == 0) {
                                    bean_add = gson.fromJson(json_name, ListBean.Bean.class);
                                    file_size += bean_add.getDownloaded_bytes();
                                } else {
                                    ListBean.Bean bean = gson.fromJson(json_name, ListBean.Bean.class);
                                    file_size += bean.getDownloaded_bytes();
                                }

                                count++;
                            }

                        }

                    }
                    if (bean_add != null) {
                        bean_add.setCount_p(count);
                        bean_add.setDownloaded_bytes(file_size);
                        count = 0;
                        file_size = 0;
                        bean_list.add(bean_add);
                    }
                }

            }

        }
    }

    class SimpleAdapter extends BaseQuickAdapter<ListBean.Bean, BaseViewHolder> {


        public SimpleAdapter(@Nullable List<ListBean.Bean> data) {
            super(R.layout.recycler_item, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, ListBean.Bean item) {
            TextView tv_count = helper.getView(R.id.tv_count);
            tv_count.getBackground().setAlpha(100);

            ImageView iv_cover = helper.getView(R.id.iv_cover);
            Glide.with(MainActivity.this).load(item.getCover()).into(iv_cover);

            String size;
            long bytes = item.getDownloaded_bytes();
            if (bytes < 1024) {
                size = bytes + "bytes";
            } else if (bytes < 1024 * 1024) {
                size = bytes / 1024 + "KB";
            } else if (bytes < 1024 * 1024 * 1024) {
                DecimalFormat decimalFormat = new DecimalFormat(".00");
                String Mb = decimalFormat.format(bytes / 1024.00 / 1024.00);
                size = Mb + "MB";
            } else {
                DecimalFormat decimalFormat = new DecimalFormat(".00");
                String Gb = decimalFormat.format(bytes / 1024.00 / 1024.00 / 1024.00);
                size = Gb + "GB";
            }

            helper.setText(R.id.tv_title, item.getTitle())
                    .setText(R.id.tv_comment, String.valueOf(item.getDanmaku_count()))
                    .setText(R.id.tv_file, size)
                    .setText(R.id.tv_count, String.valueOf(item.getCount_p()));
        }
    }

    public void showDialog(final String string, final int position){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        final View layout = inflater.inflate(R.layout.dialog_merge, null);//获取自定义布局
        builder.setView(layout);
        ((TextView)layout.findViewById(R.id.title)).setText(string);
        //builder.setMessage("");//显示自定义布局内容
        final AlertDialog dlg = builder.create();
        dlg.setCanceledOnTouchOutside(false);
        dlg.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                return true;
            }
        });
        CheckBox convert_danmu = (CheckBox) layout.findViewById(R.id.convert_danmu);
        CheckBox delete_resource = (CheckBox) layout.findViewById(R.id.delete_resource);
        Button negtiveButton = (Button) layout.findViewById(R.id.negtiveButton);
        Button positiveButton = (Button)layout.findViewById(R.id.positiveButton);

        negtiveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_all_check.setChecked(false);
                dlg.dismiss();
            }
        });

        positiveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (string.equals("确定合并该视频吗？")){
                    merge_one(position);
                }else {
                    merge_all();
                    cb_all_check.setChecked(false);
                }
                dlg.dismiss();
            }
        });

        dlg.show();
    }

    private void merge_all() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String path = c.getExternalCacheDir().getParentFile().getAbsolutePath()
                        + "/download";
                String newPath = out.getAbsolutePath() + "/copy";

                //复制
                dialogHandler.obtainMessage(CustomDialogFragment.CONTINUE,
                        "开始复制原文件...").sendToTarget();
                try {
                    FileUtils.copy(path,newPath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                dialogHandler.obtainMessage(CustomDialogFragment.CONTINUE,
                        "开始合并...").sendToTarget();
                    File file = new File(newPath);
                    File[] files = file.listFiles();
                    if (files != null && files.length > 0) {

                        for (File f : files) {
                            //1、2、3、4...分p
                            if (f.isDirectory()) {
                                showAlertDialog();
                                tool.doMerge(f,out,dialogHandler);
                                FileUtils.deleteFolder(f);
                                break;
                            }
                        }
                    }

            }
        }).start();
    }
}
